import * as winston from 'winston'
import * as path from 'path'
import * as WinstoneDailyRotateFile from 'winston-daily-rotate-file'

/**
 * 创建winston日志记录器
 * @param option
 */
export function createWinstonLogger(option: { storeRoot: string }) {
  // 获取存储根目录
  const storeRoot = path.isAbsolute(option.storeRoot) ? option.storeRoot : path.join(__dirname, option.storeRoot)

  // 构建printf格式化函数
  const printfFormat = buildPrintfFormat()

  // 构建文件格式化函数
  const fileFormat = winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss',
    }),
    winston.format.splat(),
    printfFormat
  )

  // 构建控制台格式化函数
  const consoleFormat = winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss.SSS',
    }),
    winston.format.splat(),
    winston.format.colorize(),
    printfFormat
  )

  // 创建日志记录器
  return winston.createLogger({
    levels: winston.config.npm.levels,
    exitOnError: false,
    transports: [
      // 控制台输出
      new winston.transports.Console({
        format: consoleFormat,
      }),
      // 错误日志文件输出
      new WinstoneDailyRotateFile({
        level: 'error',
        dirname: storeRoot,
        filename: 'error-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxSize: '20m',
        maxFiles: '28d',
        format: fileFormat,
      }),
      // 输出日志文件输出
      new WinstoneDailyRotateFile({
        dirname: storeRoot,
        filename: 'output-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxSize: '100m',
        maxFiles: '28d',
        format: fileFormat,
      }),
    ],
  })
}

/**
 * 格式化日志输出
 * @returns
 */
export function buildPrintfFormat() {
  return winston.format.printf(data => {
    // 构建日志消息数组
    const messages = [`${data.timestamp} ${data.level}【${data.context || '/'}】 - ${data.message}`]
    if (data.stack) {
      messages.push(data.stack)
    }
    // 拼接日志消息
    return messages.join('\n')
  })
}
